package com.example.forum.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web安全配置，处理跨域和安全策略
 */
@Configuration
public class WebSecurityConfig implements WebMvcConfigurer {

    /**
     * 配置跨域资源共享
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .maxAge(3600);
    }

    /**
     * 添加资源处理器，让上传的图片可以通过URL直接访问
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置上传目录的访问路径
        registry.addResourceHandler("/upload/**")
                .addResourceLocations("file:upload/")  // 相对于项目目录
                .setCachePeriod(3600)  // 缓存一小时
                .resourceChain(true);
    }
} 